package com.zby.business.view;

import android.content.Context;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewTreeObserver;
import android.widget.ImageView;

/**
 * Created by BY on 2016/1/4.
 */
public class ZoomImageView extends ImageView implements ViewTreeObserver.OnGlobalLayoutListener, ScaleGestureDetector.OnScaleGestureListener, View.OnTouchListener {
    private boolean firstIn;
    private float mInitScale;
    private float mMIdScale;
    private float mMaxScale;
    private Matrix matrix;

    //移动
    private int lastPointCount;
    private float lastX;
    private float lastY;
    private int mTouchSlop;
    private ScaleGestureDetector scaleGestureDetector;

    private boolean isCanDrag;
    private RectF matrixRectF;
    private boolean checkLeftAndRight;
    private boolean checkTopAndBottom;

    private GestureDetector gestureDetector;
    private boolean isAutoScale;

    public ZoomImageView(Context context) {
        this(context, null);
    }

    public ZoomImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ZoomImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        matrix = new Matrix();
        setScaleType(ScaleType.MATRIX);
        scaleGestureDetector = new ScaleGestureDetector(context, this);
        setOnTouchListener(this);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onDoubleTap(MotionEvent e) {
                if (isAutoScale) return true;
                float x = e.getX();
                float y = getHeight()/2;
                if (getScale() < mMIdScale) {
//                    matrix.postScale(mMIdScale / getScale(), mMIdScale / getScale(), x, y);
//                    setImageMatrix(matrix);
                    postDelayed(new AutoScaleRunnable(mMIdScale, x, y), 16);
                    isAutoScale = true;
                } else {
//                    matrix.postScale(mInitScale / getScale(), mInitScale / getScale(), x, y);
//                    setImageMatrix(matrix);
                    postDelayed(new AutoScaleRunnable(mInitScale, x, y), 16);
                    isAutoScale = true;
                }

                return true;
            }
        });
    }

    private class AutoScaleRunnable implements Runnable {
        private float targetScale;
        private float x;
        private float y;

        private final float BIGGER = 1.07f;
        private final float SMALL = 0.93f;

        private float tmpScale;

        public AutoScaleRunnable(float targetScale, float x, float y) {
            this.targetScale = targetScale;
            this.x = x;
            this.y = y;
            if (getScale() < targetScale) {
                tmpScale = BIGGER;
            }
            if (getScale() > targetScale) {
                tmpScale = SMALL;
            }
        }

        @Override
        public void run() {
            matrix.postScale(tmpScale, tmpScale, x, y);
            checkBorder();
            setImageMatrix(matrix);
            float currentScale = getScale();
            if ((tmpScale > 1.0f && currentScale < targetScale) || tmpScale < 1.0f && currentScale > targetScale) {
                postDelayed(this, 16);
            } else {
                float scale = targetScale / currentScale;
                matrix.postScale(scale, scale, x, y);
                checkBorder();
                setImageMatrix(matrix);
                isAutoScale = false;
            }
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        getViewTreeObserver().addOnGlobalLayoutListener(this);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        getViewTreeObserver().removeOnGlobalLayoutListener(this);
    }

    @Override
    public void onGlobalLayout() {

        if (!firstIn) {
            int width = getWidth();
            int height = getHeight();
            Drawable d = getDrawable();
            if (d == null) {
                return;
            }
            int dw = d.getIntrinsicWidth();
            int dh = d.getIntrinsicHeight();
            float scale = 1.0f;
            if (dw > width && dh < height) {
                scale = width * 1.0f / dw;
            }
            if (dh > height && dw < width) {
                scale = height * 1.0f / dh;
            }
            if ((dw > width && dh > height) || (dw < width && dh < height)) {
                scale = Math.min(width * 1.0f / dw, height * 1.0f / dw);
            }
            mInitScale = scale;
            mMaxScale = mInitScale * 4;
            mMIdScale = mInitScale * 2;
            firstIn = true;

            int dx = getWidth() / 2 - dw / 2;
            int dy = getHeight() / 2 - dh / 2;
            matrix.postTranslate(dx, dy);
            matrix.postScale(mInitScale, mInitScale, width / 2, height / 2);
            setImageMatrix(matrix);
        }
    }

    public float getScale() {
        float[] values = new float[9];
        matrix.getValues(values);
        return values[Matrix.MSCALE_X];
    }

    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        float scale = getScale();
        float scaleFactor = detector.getScaleFactor();
        if (getDrawable() == null) return true;
        if ((scale < mMaxScale && scaleFactor > 1.0f) || (scale > mInitScale && scaleFactor < 1.0f)) {
            if (scale * scaleFactor < mInitScale) {
                scaleFactor = mInitScale / scale;
            }
            if (scale * scaleFactor > mMaxScale) {
                scaleFactor = mMaxScale / scale;
            }
            matrix.postScale(scaleFactor, scaleFactor, detector.getFocusX(), detector.getFocusY());
            zoomInCenter();
            setImageMatrix(matrix);
        }

        return true;
    }

    private void zoomInCenter() {
        RectF rect = getMatrixRectF();
        float deltaX = 0;
        float deltaY = 0;
        int width = getWidth();
        int height = getHeight();
        if (rect.width() >= width) {
            if (rect.left > 0) {
                deltaX = -rect.left;
            }
            if (rect.right < width) {
                deltaX = width - rect.right;
            }
        }
        if (rect.height() >= height) {
            if (rect.top > 0) {
                deltaY = -rect.top;
            }
            if (rect.bottom < height) {
                deltaY = width - rect.right;
            }
        }
        if (rect.width() < width) {
            deltaX = width / 2 - rect.right + rect.width() / 2;
        }
        if (rect.height() < height) {
            deltaY = height / 2 - rect.bottom + rect.height() / 2;
        }
        matrix.postTranslate(deltaX, deltaY);
    }

    private RectF getMatrixRectF() {
        Matrix m = matrix;
        RectF rectF = new RectF();
        Drawable d = getDrawable();
        if (d != null) {
            rectF.set(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
            m.mapRect(rectF);
        }
        return rectF;
    }


    @Override
    public boolean onScaleBegin(ScaleGestureDetector detector) {
        return true;
    }

    @Override
    public void onScaleEnd(ScaleGestureDetector detector) {

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (gestureDetector.onTouchEvent(event))
            return true;
        scaleGestureDetector.onTouchEvent(event);
        float x = 0;
        float y = 0;
        int pointCount = event.getPointerCount();
        for (int i = 0; i < pointCount; i++) {
            x += event.getX(i);
            y += event.getY(i);
        }
        x /= pointCount;
        y /= pointCount;
        if (lastPointCount != pointCount) {
            isCanDrag = false;
            lastX = x;
            lastY = y;
        }
        lastPointCount = pointCount;
        switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:
                float dx = x - lastX;
                float dy = y - lastY;
                if (!isCanDrag) {
                    isCanDrag = isMoveAction(dx, dy);
                }
                if (isCanDrag) {
                    RectF rectF = getMatrixRectF();
                    if (getDrawable() != null) {
                        checkLeftAndRight = checkTopAndBottom = true;
                        if (rectF.width() < getWidth()) {
                            checkLeftAndRight = false;
                            dx = 0;
                        }
                        if (rectF.height() < getHeight()) {
                            checkTopAndBottom = false;
                            dy = 0;
                        }
                        matrix.postTranslate(dx, dy);
                        checkBorder();
                        setImageMatrix(matrix);
                    }
                }
                lastX = x;
                lastY = y;
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                lastPointCount = 0;
                break;
        }
        return true;
    }

    private void checkBorder() {
        RectF rectF = getMatrixRectF();
        float deltaX = 0;
        float deltaY = 0;
        int width = getWidth();
        int height = getHeight();
        if (rectF.top > 0 && checkTopAndBottom) {
            deltaY = -rectF.top;
        }
        if (rectF.bottom < height && checkTopAndBottom) {
            deltaY = height - rectF.bottom;
        }
        if (rectF.left > 0 && checkLeftAndRight) {
            deltaX = -rectF.left;
        }
        if (rectF.right < width && checkLeftAndRight) {
            deltaX = width - rectF.right;
        }
        matrix.postTranslate(deltaX, deltaY);
        setImageMatrix(matrix);
    }

    private boolean isMoveAction(float dx, float dy) {

        return Math.sqrt(dx * dx + dy * dy) > mTouchSlop;
    }
}
